<template>
  <div class="courses-page">
    <div class="page-header">
      <h2 class="page-title">课程管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加课程
      </el-button>
    </div>

    <!-- 课程表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="appStore.courses" stripe class="courses-table">
        <el-table-column prop="code" label="课程代码" width="120" />
        <el-table-column prop="name" label="课程名称" />
        <el-table-column prop="credits" label="学分" width="80" />
        <el-table-column prop="teacher" label="任课教师" width="120" />
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getCourseTypeColor(row.code)">
              {{ getCourseType(row.code) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag type="success">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click="viewCourse(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button size="small" type="primary" @click="editCourse(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="deleteCourse(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      :title="isEditing ? '编辑课程' : '添加课程'"
      v-model="showAddDialog"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="课程代码" prop="code">
          <el-input v-model="courseForm.code" placeholder="请输入课程代码" />
        </el-form-item>
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseForm.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="学分" prop="credits">
          <el-input-number v-model="courseForm.credits" :min="1" :max="6" />
        </el-form-item>
        <el-form-item label="任课教师" prop="teacher">
          <el-input v-model="courseForm.teacher" placeholder="请输入任课教师" />
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input
            v-model="courseForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入课程描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            {{ isEditing ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 课程详情对话框 -->
    <el-dialog
      title="课程详情"
      v-model="showDetailDialog"
      width="600px"
    >
      <div v-if="selectedCourse" class="course-detail">
        <div class="detail-header">
          <h3>{{ selectedCourse.name }}</h3>
          <el-tag type="primary">{{ selectedCourse.code }}</el-tag>
        </div>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程代码">
            {{ selectedCourse.code }}
          </el-descriptions-item>
          <el-descriptions-item label="课程名称">
            {{ selectedCourse.name }}
          </el-descriptions-item>
          <el-descriptions-item label="学分">
            {{ selectedCourse.credits }}
          </el-descriptions-item>
          <el-descriptions-item label="任课教师">
            {{ selectedCourse.teacher }}
          </el-descriptions-item>
          <el-descriptions-item label="课程类型">
            <el-tag :type="getCourseTypeColor(selectedCourse.code)">
              {{ getCourseType(selectedCourse.code) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag type="success">正常</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="course-stats">
          <h4>课程统计</h4>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-statistic title="选课学生" :value="getEnrolledStudents(selectedCourse)" suffix="人" />
            </el-col>
            <el-col :span="8">
              <el-statistic title="平均成绩" :value="getAverageScore(selectedCourse)" :precision="1" suffix="分" />
            </el-col>
            <el-col :span="8">
              <el-statistic title="及格率" :value="getPassRate(selectedCourse)" :precision="1" suffix="%" />
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '../stores/app'

const appStore = useAppStore()

const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const isEditing = ref(false)
const selectedCourse = ref(null)
const courseFormRef = ref()

// 课程表单数据
const courseForm = reactive({
  id: null,
  code: '',
  name: '',
  credits: 3,
  teacher: '',
  description: ''
})

// 表单验证规则
const formRules = {
  code: [
    { required: true, message: '请输入课程代码', trigger: 'blur' },
    { pattern: /^[A-Z]{2,4}\d{3}$/, message: '课程代码格式不正确，如：CS101', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  credits: [
    { required: true, message: '请输入学分', trigger: 'blur' }
  ],
  teacher: [
    { required: true, message: '请输入任课教师', trigger: 'blur' }
  ]
}

// 方法
const getCourseType = (code) => {
  if (code.startsWith('MATH')) return '数学类'
  if (code.startsWith('CS')) return '计算机类'
  if (code.startsWith('ENG')) return '英语类'
  return '其他'
}

const getCourseTypeColor = (code) => {
  if (code.startsWith('MATH')) return 'primary'
  if (code.startsWith('CS')) return 'success'
  if (code.startsWith('ENG')) return 'warning'
  return 'info'
}

const getEnrolledStudents = (course) => {
  return Math.floor(Math.random() * 50) + 20 // 模拟数据
}

const getAverageScore = (course) => {
  return Math.floor(Math.random() * 20) + 75 // 模拟数据
}

const getPassRate = (course) => {
  return Math.floor(Math.random() * 20) + 80 // 模拟数据
}

const viewCourse = (course) => {
  selectedCourse.value = course
  showDetailDialog.value = true
}

const editCourse = (course) => {
  isEditing.value = true
  showAddDialog.value = true
  Object.assign(courseForm, course)
}

const deleteCourse = async (course) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除课程"${course.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 从课程列表中删除
    const index = appStore.courses.findIndex(c => c.id === course.id)
    if (index !== -1) {
      appStore.courses.splice(index, 1)
    }
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  try {
    await courseFormRef.value.validate()
    
    if (isEditing.value) {
      // 更新课程
      const index = appStore.courses.findIndex(c => c.id === courseForm.id)
      if (index !== -1) {
        Object.assign(appStore.courses[index], courseForm)
      }
      ElMessage.success('更新成功')
    } else {
      // 添加课程
      const newCourse = {
        ...courseForm,
        id: Date.now()
      }
      appStore.courses.push(newCourse)
      ElMessage.success('添加成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(isEditing.value ? '更新失败' : '添加失败')
    }
  }
}

const resetForm = () => {
  isEditing.value = false
  Object.assign(courseForm, {
    id: null,
    code: '',
    name: '',
    credits: 3,
    teacher: '',
    description: ''
  })
  if (courseFormRef.value) {
    courseFormRef.value.resetFields()
  }
}

// 生命周期
onMounted(async () => {
  try {
    await appStore.fetchCourses()
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
})
</script>

<style scoped>
.courses-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-weight: 500;
}

.table-card {
  border-radius: 8px;
}

.courses-table {
  width: 100%;
}

.action-buttons {
  display: flex;
  flex-direction: row;
  gap: 8px;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: nowrap;
}

.action-buttons .el-button {
  flex-shrink: 0;
  min-width: auto;
}

.course-detail {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0;
  color: #303133;
}

.course-stats {
  margin-top: 20px;
}

.course-stats h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .courses-table {
    font-size: 12px;
  }
}
</style> 